<template lang="pug">
  el-drawer.commonDrawer(
    title="选择课程"
    :visible="visibleDialog"
    custom-class="courseSelector"
    size="50%"
    append-to-body
    direction="rtl"
    @close="$_handleCancel"
  )
    .courseWrapper
      el-tabs.courseBox.commonTab(v-model="curCategory")
        el-tab-pane(v-for="course in courses" :key="course.type" :name="course.type" :label="course.label")
          s-table(
            v-if="course.type !== '0'"
            ref="table"
            reqUrl="web/course_early/course_page_by_type"
            :show-header="false"
            :column="tableObj.column"
            :pageSize="10"
            size="small"
            :filterProps="{fields: course.type === '3' ? searchFieldSystem : searchFieldArea}"
            :queryPropsParams="{areaId: curArea.areaId, courseType: course.type, packageType: packageType}"
            @row-click="rowClickHandle"
          )
            template(slot="name" slot-scope="text, scope")
              el-radio(v-model="selectId" :label="scope.id" class="radioColumn")
                | {{text}}
                //- 自建课和活动课可以删除
              el-button.delete(v-if="curCategory !== '3'" icon="el-icon-close" circle size="mini" @click.stop="() => delCourse(scope)")
          el-input(v-else v-model="activityContent" size="small" placeholder="请输入课程名称")
    .footer.tr
      //- 自建课和活动课可以添加
      <!--el-button(v-if="curCategory !== '3'" size="large" type="success" @click="addHandle" plain round) 添加-->
      el-button.gradientVertical(size="large" @click="sureHandle" round) 确定
    activity-add(:visible.sync="modalObj.visible" v-if="modalObj.type === 'activity'")
</template>
<script>
import { mapGetters } from 'vuex'
import shortid from 'shortid'
import uniqBy from 'lodash/uniqBy'
import { columnConfig, seachConfig } from './config'
import { getCourseTypeByName } from '../../api'
import ActivityAdd from './activityAdd'
import { state } from '@/store/modules/dict'
import { getCourseDict } from '@/views/educational/courseManage/teachPlan/api'

export default {
  components: {
    ActivityAdd
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    // 初始课程信息
    initCourse: {
      type: Object,
      default: () => (null)
    },
    courses: {
      type: Array,
      default: () => state.dict.courseCategory
    },
    packageType: {
      type: String,
      default: '0'
    }
  },
  data () {
    return {
      curCategory: '3',
      tableObj: {
        column: columnConfig,
        seachConfig: seachConfig()
      },
      typeNames: [], // 课程类型下拉选择
      selectId: '',
      selectRow: null,
      modalObj: {
        visible: false,
        type: ''
      },
      activityContent: '',

      areaTypeNames: [],

      monthList: [],
      faceList: [],
      weekList: []
    }
  },
  computed: {
    ...mapGetters(['dict', 'curArea']),
    searchFieldSystem () {
      if (this.packageType === '2') {
        return [
          {
            key: 'monthAge',
            label: '月龄',
            type: 'select',
            fieldProps: {
              options: this.monthList,
              props: { value: 'dictValue', label: 'dictLabel' }
            }
          },
          {
            key: 'week',
            label: '请选择周次',
            type: 'select',
            fieldProps: {
              options: this.weekList,
              props: { value: 'dictValue', label: 'dictLabel' }
            }
          },
          {
            key: 'name',
            label: '请输入课程名称'
          }
        ]
      } else {
        return [
          {
            key: 'monthAge',
            label: '月龄',
            type: 'select',
            fieldProps: {
              options: this.monthList,
              props: { value: 'dictValue', label: 'dictLabel' }
            }
          },
          {
            label: '请选择面向类别',
            key: 'courseFace',
            type: 'select',
            fieldProps: {
              options: this.faceList,
              props: { value: 'dictValue', label: 'dictLabel' }
            }
          },
          {
            key: 'courseWeek',
            label: '请选择周次',
            type: 'select',
            fieldProps: {
              options: this.weekList,
              props: { value: 'dictValue', label: 'dictLabel' }
            }
          },
          {
            key: 'name',
            label: '请输入课程名称'
          }
        ]
      }
    },
    searchFieldArea () {
      const options = this.areaTypeNames
      console.log(options)
      return [
        {
          key: 'typeName',
          label: '课程类型',
          type: 'select',
          fieldProps: {
            options: options,
            props: { value: 'value', label: 'label' }
          }
        },
        {
          key: 'name',
          label: '课程名称'
        }
      ]
    },
    visibleDialog: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    },
    course: {
      get () {
        return this.initCourse
      },
      set (val) {
        this.$emit('update:initCourse', val)
      }
    }
    // courses () {
    //   return this.dict.courseCategory
    // }
  },
  watch: {
    initCourse: {
      handler (val) {
        if (val) {
          this.curCategory = val?.courseType || '3'
          this.selectRow = val
          this.selectId = val.resObj
          this.activityContent = ''
        }
      },
      immediate: true
    }
  },
  created () {
    // this.courses.forEach(x => {
    //   this.getFilterItems(x.type)
    // })
    this.getFilterItemsByArea()
    this.getCourseDict()
  },
  methods: {
    refreshTable (flag = false) {
      console.log(this.$refs.table)
      this.$refs.table && this.$refs.table.refresh(flag)
    },
    rowClickHandle (row) {
      const { curCategory } = this
      this.selectId = row.id
      this.selectRow = { ...row, courseType: curCategory, category: this.courses.find(x => x.type === curCategory).category }
    },
    getFilterItemsByArea () {
      const { curArea } = this
      const areaId = curArea.areaId
      getCourseTypeByName({ areaId }, { courseType: 2 }).then(res => {
        console.log(res)
        const list = (res || []).map(x => {
          x.value = x.typeName
          x.label = x.typeName
          return x
        })
        this.areaTypeNames = uniqBy(list, 'value')
        console.log(this.areaTypeNames)
      })
    },
    async getFilterItems (courseType) {
      const { curArea } = this
      const areaId = curArea.areaId
      const res = await getCourseTypeByName({ areaId }, { courseType })
      console.log(res)
      const list = (res || []).map(x => {
        x.value = x.typeName
        x.label = x.typeName
        return x
      })
      this.typeNames[courseType] = seachConfig(uniqBy(list, 'value'))
      console.log(this.typeNames)
    },
    // 删除课程
    delCourse (row) {
      console.log(row)
    },
    // 添加课程
    addHandle () {
      const { curCategory } = this
      // 自建课跳转到自建课添加页面
      if (curCategory === '2') {
        this.$router.push('/')
      }
      // 弹出活动课添加弹窗
      if (curCategory === '0') {
        this.modalObj = {
          visible: true,
          type: 'activity'
        }
      }
    },
    $_handleCancel () {
      this.visibleDialog = false
      this.selectRow = null
      this.selectId = ''
    },
    // 确认课程选择
    sureHandle () {
      const { selectRow, initCourse } = this
      const { curCategory } = this

      let activityContent = selectRow.name
      if (this.curCategory === '0') {
        activityContent = this.activityContent
      }

      const course = {
        // ...this.course,
        ...selectRow,
        begin: this.course.begin,
        end: this.course.end,
        id: initCourse?.id || '',
        activityContent: activityContent,
        resObj: selectRow.id,
        remark: this.course.remark || ''
      }
      if (!initCourse?.id) {
        course.id = shortid.generate()
        course.isAdd = true
      }
      if (curCategory === '0') {
        course.category = 0
      }
      this.course = course
      this.$emit('sureHandle', course, !initCourse?.id)
      this.$_handleCancel()
    },

    getCourseDict () {
      getCourseDict({ dictType: 'tc_month', type: this.packageType }).then(res => {
        this.monthList = res
      })
      if (this.packageType === '0') {
        getCourseDict({ dictType: 'tc_face', type: this.packageType }).then(res => {
          this.faceList = res
        })
      } else if (this.packageType === '1') {
        getCourseDict({ dictType: 'tc_face', type: this.packageType }).then(res => {
          this.faceList = res
        })
      }
      getCourseDict({ dictType: 'tc_week', type: this.packageType }).then(res => {
        this.weekList = res
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.courseSelector{
  .el-drawer__header{
    margin-bottom: 10px;
  }

  .footer{
    position: absolute;
    bottom: 16px;
    left: 16px;
    right: 16px
  }

}

.radioColumn{
  .el-radio__label{
    display: none;
  }
}

.courseWrapper{
  padding: 0 20px;
  position: relative;
  margin-top: -20px;
  .courseBox{

    max-height: calc(100vh - 106px);

    ::v-deep{

      .tableWrapper{
        padding: 0;
        margin-bottom: 24px;

        td {
          height: 60px;
          font-size: 15px;
          color: #333333;
          border-bottom-style: dashed;

          .el-radio__input{
            &.is-checked{
              .el-radio__inner{
                border-color: #DA473A;
                background: #DA473A;
              }
              + .el-radio__label{
                color: #DA473A
              }
            }
          }
        }

      }

    }

    .delete{
      padding: 3px;
      position: absolute;
      right: 0
    }

  }

}

</style>
